package com.lishe.lishe.lishe.MyRecyclerView;

import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

/**
 * Created by shino on 2017/9/28.
 */

public class RecyclerGriadViewItemDecoration extends RecyclerView.ItemDecoration {
    int headerCount;
    int foorderCount;
    int space;//间隔

    public RecyclerGriadViewItemDecoration(int space, int headerCount, int foorderCount) {
        this.headerCount = headerCount;
        this.foorderCount = foorderCount;
        this.space = space;
    }

    /**
     * 获取列数
     *
     * @param parent
     * @return
     */
    private int getSpanCount(RecyclerView parent) {
        // 列数
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }

    private int getItemCount(RecyclerView parent) {
        // 列数
        int itemCount = -1;
        RecyclerView.Adapter adapter = parent.getAdapter();
        itemCount = adapter.getItemCount();
        return itemCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        int spanCount = getSpanCount(parent);
        int itemCoubt = getItemCount(parent);
        if (position >= headerCount && position < itemCoubt - foorderCount) {//暂时不兼容存在footview
            int index = (position - headerCount) % spanCount;
            if (index == 0) {//第一列
                outRect.left = space;
                outRect.right = space / 2;
            } else if (index == spanCount-1) {//最后一列
                outRect.left = space / 2;
                outRect.right = space;
            } else {//中间列
                outRect.left = space / 2;
                outRect.right = space / 2;
            }
            outRect.bottom = space;
        }
    }
}
